package cn.ihoway.room;

import cn.ihoway.annotation.Processor;
import cn.ihoway.common.CommonProcessor;
import cn.ihoway.entity.Allocation;
import cn.ihoway.entity.Room;
import cn.ihoway.redis.AllocationRedis;
import cn.ihoway.redis.RoomRedis;
import cn.ihoway.room.io.RoomExitInput;
import cn.ihoway.room.io.RoomExitOutput;
import cn.ihoway.socket.GameSessionManager;
import cn.ihoway.type.NotifyType;
import cn.ihoway.type.StatusCode;
import cn.ihoway.util.HowayLog;
import cn.ihoway.util.HowayMessage;
import cn.ihoway.util.HowayWsResult;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 玩家主动或者被动退出房间
 * 该玩家后面序号玩家自动前进
 * 房间玩家为0时解散房间
 * 注：房主id始终是1
 */
@Processor(name = "RoomExitProcessor")
public class RoomExitProcessor  extends CommonProcessor<RoomExitInput, RoomExitOutput> {
    private final HowayLog logger = new HowayLog(RoomExitProcessor.class);
    private final RoomRedis roomRedis = new RoomRedis();
    private final AllocationRedis allocationRedis = new AllocationRedis();

    @Override
    protected StatusCode dataCheck(RoomExitInput input){
        return StatusCode.SUCCESS;
    }
    
    @Override
    protected HowayWsResult process(RoomExitInput input, RoomExitOutput output) throws IOException {
        GameSessionManager.remove(input.inChomm.sessionId);
        Allocation allocationPre = allocationRedis.getBySessionId(input.inChomm.sessionId);
        //获取退出玩家的id
        String playerId = allocationPre.getPlayerId();
        String roomId = allocationPre.getRoomId();

        Room room = roomRedis.get(roomId);
        //获取房间当前人数
        Integer num = room.getCurrentNum();

        int start = Integer.parseInt(playerId);
        //系统分配表删除该玩家
        allocationRedis.remove(allocationPre);
        //该玩家后面的同房间内的玩家的id前移一个
        List<Allocation> list = allocationRedis.searchMore(roomId,start);
        for(Allocation allocation : list){
            playerId = allocation.getPlayerId();
            String newPlayerId = String.valueOf(Integer.parseInt(playerId)-1);
            allocation.setPlayerId(newPlayerId);
            //更新玩家id
            allocationRedis.update(allocation);
        }
        //更新房间信息
        room.setCurrentNum(num-1);
        roomRedis.put(roomId,room);
        ArrayList<WebSocketSession> sessions = GameSessionManager.getFromRoom(roomId);
        for(WebSocketSession socketSession: sessions){
            HowayMessage message = new HowayMessage("用户" + input.inChomm.sessionId + "退出房间");
            socketSession.sendMessage(new TextMessage(message.toString()));
        }
        return HowayWsResult.createSuccessResult(output);
    }
}